class TreeNode(object):
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right


class Solution(object):
    def leafSimilar(self, root1, root2):
        """
        :type root1: TreeNode
        :type root2: TreeNode
        :rtype: bool
        """
        out = [[], []]

        def search(node, k):
            if not node.left and not node.right:
                out[k].append(node.val)
            if node.left:
                search(node.left, k)
            if node.right:
                search(node.right, k)

        search(root1, 0)
        search(root2, 1)
        if out[0] == out[1]:
            return True
        else:
            return False

